<!-- 通知公告 -->
<template>
  <div class="module_ news">
    <div class="mb8">
      <search @clearSearch='clearSearch'>
        <el-form label-width='80px' inline autocomplete="off"  :model="pageparm" class="search_box">
          <el-form-item label="文件名称">
            <el-input size="medium" clearable v-model="pageparm.name" placeholder="请输入文件名称搜索"/>
          </el-form-item>
          <el-form-item label="文件类型">
            <el-select size="medium" clearable v-model="pageparm.document_type" placeholder="请选择文件类型搜索" @change='searchChane($event,"document_type")'>
              <el-option
                v-for="item in documentType"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布人">
            <inputSearch :options="{type:'search'}" ref="search_e" placeholder="请输入发布人姓名搜索" @onChange='searchChane($event,"employees_id")'  />
          </el-form-item> 
        </el-form>
        <template slot="footer" class="flex">
          <el-button v-if="adminShow" class="mr8" size="medium" type="primary" @click="handle()">文件上传</el-button>
        </template>
      </search>
    </div>
    <el-table
      :data="tableData"
      height="100%"
      size="medium"
      border
      highlight-current-row
      v-loading="tableLoading"
      @sort-change="tableSortChange"
      stripe>
      <el-table-column
        align="center"
        prop="name"
        label="文件"
        width="220"
        sortable="custom"
        show-overflow-tooltip>
        <template slot-scope="scope">
          <!-- <el-image
            v-if="isIMage(scope.row.name)"
            :z-index='3000'
            class="image"
            :src="uploadUrl + scope.row.file_path" 
            :preview-src-list="[uploadUrl + scope.row.file_path]">
          </el-image> -->
          <span class="shou xialine" @click="downloadFiles(scope.row)"><i :class="['iconfont',isLoading(scope.row.id)]"></i> {{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="document_type"
        label="文件类型"
        width="120"
        sortable="custom">
        <template slot-scope="scope">
          {{scope.row.document_type === 1?'文档':'图片'}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="employees_id"
        label="发布人"
        width="150"
        sortable="custom">
        <template slot-scope="scope">
          {{scope.row.employee?scope.row.employee.name:''}}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="created_at"
        label="上传时间"
        width="200"
        sortable="custom">
      </el-table-column>
      <el-table-column
        align="center"
        prop="description"
        label="文件说明"
        min-width="250"
        sortable="custom">
      </el-table-column>
      <el-table-column
        align="center"
        prop="download_count"
        label="下载次数"
        width="115"
        sortable="custom">
      </el-table-column>
      <el-table-column v-if="adminShow"  align="center" label="操作" width="125">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="删除" placement="bottom-end">
            <el-button
              size="small"
              type="danger"
              @click="deleteUser(scope.$index, scope.row)"
              icon="el-icon-delete"
              circle
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-image-viewer
      v-if="imgObj.showImg"
      :on-close="()=>{imgObj.showImg=false}"
      :url-list="imgObj.urlList" />
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>

    <el-dialog
      class="dialog"
      :visible.sync="editFormVisible"
      width="800px"
      @click="editFormVisible = false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close='dialogClose'>
      <el-form autocomplete="off"  label-width="80px" label-position="right" :model="editForm" class="content" >
        <el-form-item label="附件" class="tip">
          <el-upload
            action="/"
            :on-change='onChangeFile'
            :on-remove="onRemoveFile"
            :auto-upload="false"
            accept="image/*,.xlsx,.xls,.doc,.docx,.ppt,.pptx,.pdf,.txt"
            ref="upload">
            <el-button size="medium" type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="文档说明">
          <el-input type="textarea" :autosize="{minRows: 5}" v-model="editForm.description" placeholder="请输入文档说明"> </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  Apidocuments,
  ApidocumentsAdd,
  ApidocumentsDel,
  ApidocumentsDown
} from "@/api";
import { debounce,adminShow } from "@/utils";
import {isIMage,allowFiles} from '@/utils/test'
import multipleSearch from '@/components/multipleSearch'
import {uploadUrl} from '@/api/request'
// import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  components:{
    multipleSearch,
    // ElImageViewer
  },
  data() {
    return {
      uploadUrl:uploadUrl(),
      adminShow:adminShow(),
      isIMage,
      tableData: [],
      editFormVisible: false,
      editForm: {
        document_type: '',
        description: ''
      }, //修改
      pageparm: {
        page: 1,
        perPage: 20,
        total: null,
        sort_str: null,
        sort_order: null,
      },
      tableLoading: false,

      files:null,

      imgObj:{
        urlList:[],
        showImg: false
      },

      documentType:[{
        label: '文档',
        value: 1
      },{
        label: '图片',
        value: 2
      }],

      loadingList:[]

    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    isLoading(id){
      const flag = this.loadingList.includes(id)
      return flag ? 'el-icon-loading' : 'icon-ziyuan'
    },
    downloadFiles:debounce ( function(item){
      if(this.loadingList.includes(item.id)){
        return
      }
      this.loadingList.push(item.id)
      ApidocumentsDown(item.id).then(res => {
        this.loadingList = this.loadingList.filter(ele => ele != item.id)
        if(res.size === 0){
          this.$message({
                type: "error",
                message: "文件不存在!",
              });
        }else{
          let a = document.createElement("a")
          a.href = URL.createObjectURL(res)
          a.download = item.name 
          a.click()
          URL.revokeObjectURL(a.href)
          this.getList()
        }
      })
    },1000,true),
    dialogClose(){
      this.editForm =  {
        document_type: '',
        description: ''
      }
      this.$refs.upload.clearFiles()
      this.files = null
    },
    onChangeFile(file, fileList){
      if(!allowFiles(file.name)){
        this.$message.error('不支持上传该格式文件')
        this.$refs.upload.uploadFiles = []
        return
      }
      this.$refs.upload.uploadFiles = [file]
      this.files = file
      const flag = isIMage(file.name)
      if(flag) this.editForm.document_type = 2
      else this.editForm.document_type = 1
    },
    onRemoveFile(file, fileList){
      this.files = null
      this.editForm.document_type = null
    },
    searchChane(i,val){
      this.pageparm[val] = i
      this.pageparm.page = 1
      this.getList()
    },
    handle(index, item, i) {
      this.editFormVisible = true;
    },
    tableSortChange(column) {
      if (column.order === "descending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "desc";
      } else if (column.order === "ascending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "asc";
      } else {
        this.pageparm.sort_str = null;
        this.pageparm.sort_order = null;
      }
      this.getList();
    },
    //搜索
    clearSearch(){
      this.$refs.search_e.clear()
    },

    //分页
    callFather(pageparm) {
      this.pageparm.page = pageparm.page;
      this.pageparm.perPage = pageparm.perPage;
      this.getList();
    },
    getList() {
      this.tableLoading = true;
      Apidocuments(this.pageparm)
        .then(({ data, page }) => {
          this.tableData = data || [];
          this.pageparm.total = page.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    deleteUser(index, value) {
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: "删除中...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          ApidocumentsDel(value.id)
            .then((res) => {
              this.getList(true);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            })
            .finally(() => {
              loading.close();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submit: debounce(
      function () {
        //提交  修改或新增
        const editForm = this.editForm ;
        const loading = this.$loading({
          lock: true,
          text: "加载中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        if(!editForm.name) editForm.name = this.files.name
        const formData = new FormData()
        formData.append('employees_id', this.$store.state.userInfo.employees_id)
        formData.append('name', editForm.name)
        formData.append('document_type', editForm.document_type)
        formData.append('description', editForm.description)
        formData.append('files', this.files.raw)

        ApidocumentsAdd(formData,{
            headers:{'Content-Type':'multipart/form-data'}
        }).then(res => {
          this.$message({
            type: "success",
            message: "上传成功!",
          });
          this.editFormVisible = false;
          this.getList();
        }).catch(()=>{
          this.$message({
            type: "error",
            message: "上传失败!",
          });
        }).finally(() => {
            loading.close();
        })},
      500,
      true
    ),
  },
};
</script>

<style lang='less'>
.news{
  .content{
    .el-input,.el-textarea__inner{
      width: 500px;
    }
  }
  .files_box{
    display: inline-block;
  }
  .image{
    width: 50px;
    height: 50px;
  }
}

</style>